package com.code.qgjx.config;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * Web安全配置类，用于全局拦截请求，验证用户登录状态
 */
@Configuration
public class WebSecurityConfig extends WebMvcConfigurerAdapter{
    // 定义session中的用户信息key
    public static final String SESSION_KEY="name";

    /**
     * 创建并返回一个SecurityInterceptor实例
     * @return SecurityInterceptor实例
     */
    @Bean
    public SecurityInterceptor getSecurityInterceptor(){
        return  new SecurityInterceptor();
    }

    /**
     * 添加拦截器配置
     * @param registry 拦截器注册对象，用于添加和排除拦截路径
     */
    @Override
    public  void addInterceptors(InterceptorRegistry registry){
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());

        // 排除配置，以下路径无需登录即可访问
        addInterceptor.excludePathPatterns("/Sys/loginView","/Sys/register","/Sys/addUser","/Sys/forgotPass","/Sys/changePass","/Sys/dealLogin","/Sys/css/**","/Sys/fonts/**","/Sys/images/**","/Sys/js/**","/Sys/lau/**","/Sys/lib/**");
        // 拦截配置，所有请求都需要经过登录验证
        addInterceptor.addPathPatterns("/**/**");
    }

    /**
     * 安全拦截器，用于拦截请求，验证用户是否已登录
     */
    private class SecurityInterceptor extends HandlerInterceptorAdapter {
        /**
         * 在请求处理之前进行拦截
         * @param request 请求对象
         * @param response 响应对象
         * @param handler 处理请求的对象
         * @return boolean true表示继续执行下一个拦截器或请求处理方法，false表示中断执行
         * @throws IOException 抛出IOException异常
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws IOException{
            HttpSession session = request.getSession(true);
            // 判断是否已有该用户登录的session
            if(session.getAttribute("name") !=null){
                return  true;
            }
            // 跳转到登录页
            String url = "/Sys/loginView";
            response.sendRedirect(url);
            return false;
        }
    }
}
